package com.eagle.videoboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eagle.videoboot.domain.entity.UsersLikeVideos;
import com.eagle.videoboot.mapper.UsersLikeVideosMapper;
import com.eagle.videoboot.mapper.UsersMapper;
import com.eagle.videoboot.mapper.VideosCustomMapper;
import com.eagle.videoboot.service.IUsersLikeVideosService;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户喜欢的/赞过的视频 服务实现类
 * </p>
 *
 * @author eagle
 * @since 2020-04-22
 */
@Service
public class UsersLikeVideosServiceImpl extends ServiceImpl<UsersLikeVideosMapper, UsersLikeVideos> implements IUsersLikeVideosService {

	@Autowired(required = false)
	private Sid sid;

	@Autowired(required = false)
	private UsersMapper userMapper;

	@Autowired(required = false)
	private VideosCustomMapper videosCustomMapper;

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void userLikeVideo(String userId, String videoId, String videoCreaterId) {
		// 1. 保存用户和视频的喜欢点赞关联关系表
		String likeId = sid.nextShort();
		UsersLikeVideos ulv = new UsersLikeVideos();
		ulv.setId(likeId);
		ulv.setUserId(userId);
		ulv.setVideoId(videoId);
		this.save(ulv);

		// 2. 视频喜欢数量累加
		videosCustomMapper.addVideoLikeCount(videoId);

		// 3. 用户受喜欢数量的累加
		userMapper.addReceiveLikeCount(videoCreaterId);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void userUnLikeVideo(String userId, String videoId, String videoCreaterId) {
		// 1. 删除用户和视频的喜欢点赞关联关系表
		QueryWrapper<UsersLikeVideos> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", userId);
		wrapper.eq("video_id", videoId);
		this.remove(wrapper);

		// 2. 视频喜欢数量累减
		videosCustomMapper.reduceVideoLikeCount(videoId);

		// 3. 用户受喜欢数量的累减
		userMapper.reduceReceiveLikeCount(videoCreaterId);
	}
}
